#include <iostream>
#include <string>
#include <memory>
#include <cstring>
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/ip.h>
#include <arpa/inet.h>
#include "log.hpp"
#include"Thread.hpp"

uint16_t serverport = 0;
std::string serverip;

static void Usage(std::string proc)
{
    std::cout << "\nUsage:" << proc << "port" << std::endl;
}

static void *udpRecv(void *args)
{
    int sock = *(int*)((ThreadData*)args)->_args;
    std::string name = ((ThreadData*)args)->_name;

    char buffer[1024];
    while(1)
    {
        memset(buffer, 0, sizeof buffer);
        struct sockaddr_in temp;
        socklen_t len = sizeof temp;
        ssize_t s = recvfrom(sock, buffer, sizeof buffer, 0, (struct sockaddr*)&temp, &len);
        if(s > 0)
        {
            buffer[s] = 0;
            std::cout << buffer << std::endl;
        }
    }
}

static void *udpSend(void *args)
{
    int sock = *(int*)((ThreadData*)args)->_args;
    std::string name = ((ThreadData*)args)->_name;

    std::string message;
    struct sockaddr_in server;
    server.sin_family = AF_INET;
    server.sin_port = htons(serverport);
    server.sin_addr.s_addr = inet_addr(serverip.c_str());
    socklen_t len = sizeof server;

    while(1)
    {
        memset(&message, 0, sizeof message);
        std::cout << "请输入你想发送的信息：";
        std::getline(std::cin, message);

        if(message == "quit")
            break;

        ssize_t s = sendto(sock, &message, sizeof message, 0, (struct sockaddr*)&server, len);

    }

}

int main(int argc, char *argv[])
{
    if (argc != 2)
    {
        logMessage(FATAL, "%s", "use error");
        Usage(argv[0]);
        exit(1);
    }

    while (1)
    {
        std::string message;
        uint16_t port = atoi(argv[1]);
        int sock = socket(AF_INET, SOCK_DGRAM, 0);
        struct sockaddr_in sever;
        memset(&sever, '0', sizeof sever);
        sever.sin_family = AF_INET;
        sever.sin_port = htons(port);
        sever.sin_addr.s_addr = INADDR_ANY;

        if (bind(sock, (struct sockaddr *)&sever, sizeof sever) < 0)
        {
            logMessage(FATAL, "%s", "bind error");
            exit(2);
        }

        std::cout << "请输入你的信息：";
        std::getline(std::cin, message);
        
        sendto(sock, &message, sizeof message, 0, (struct sockaddr*)&sever, sizeof sever);

        struct sockaddr_in temp;
        bzero(&temp, sizeof temp);
        socklen_t len = sizeof temp;
        std::string recv;

        ssize_t s = recvfrom(sock, &recv, sizeof recv, 0, (struct sockaddr*)&temp, &len);
        if(s > 0)
        {
            recv[s] = 0;
            std::cout << recv << std::endl;
        }
    }
}